package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 修改员工信息
     *
     * @param employeeDTO
     * @return
     */
    @Transactional
    @Override
    public Result update(EmployeeDTO employeeDTO) {
        //非空判断
        if (employeeDTO.getId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //1.对象属性拷贝，employeeDTO到employee
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //2.补全信息
        //2.1修改时间
        //employee.setUpdateTime(LocalDateTime.now());

        //2.2修改人
        //employee.setUpdateUser(BaseContext.getCurrentId());

        //3.调用dao层
        employeeMapper.update(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Result<Employee> listById(Long  id) {
        //非空判断
        if(id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //调用Mapper层
        Employee employee = employeeMapper.listById(id);
        employee.setPassword("********");
        return Result.success(employee);
    }

    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result startOrClose(Integer status, Long id) {
        //非空判断
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        if (status == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //调用Mapper层
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
        return Result.success();
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public Result page(EmployeePageQueryDTO employeePageQueryDTO) {
        //若为空，设置默认
        if (employeePageQueryDTO.getPage() == null) {
            employeePageQueryDTO.setPage(1);
        }
        if (employeePageQueryDTO.getPageSize()==null) {
            employeePageQueryDTO.setPageSize(10);
        }

        //开始分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

        return Result.success(pageResult);
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @Transactional
    @Override
    public Result add(EmployeeDTO employeeDTO) {
        //1.非空判断
        if (employeeDTO.getUsername() == null) {
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //1.对象属性拷贝，employeeDTO到employee
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //2.补全信息
        //2.1设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //2.2设置默认开启状态
        employee.setStatus(StatusConstant.ENABLE);

        //2.3创建和修改时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //2.4创建和修改人
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        //3.调用dao层
        employeeMapper.add(employee);
        return Result.success();
    }


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Result<EmployeeLoginVO> login(EmployeeLoginDTO employeeLoginDTO) {
        if (employeeLoginDTO.getUsername()==null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //对用户输入的明文密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        String token = JwtUtil.getToken(employee.getId());

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        //3、返回实体对象
        return Result.success(employeeLoginVO);
    }
}
